package com.pwrd.sframe.netty;

import com.pwrd.sframe.conn.Connection;
import com.pwrd.sframe.support.constant.ConfigConst;
import com.pwrd.sframe.core.Port;
import com.pwrd.sframe.support.constant.ConstNode;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther syc.
 * @Date 2017/1/4 16:46.
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    //当前连接
    private Optional<Connection> conn;

    private static AtomicInteger connId = new AtomicInteger();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        int id = connId.getAndIncrement();
        int portId = id % ConfigConst.PORT_STARTUP_CONN_NUM;
        Port port = ConnServer.CONN_NODE.ports.get(ConstNode.PORT_CONN_PREFIX + portId);

        conn = Optional.of(new Connection(channel, port, id));
        conn.get().startUp();

        System.out.println("The connect build success");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);

        if (conn.isPresent()) conn.get().recvHandler(bytes);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (!conn.isPresent()) return;
    }
}
